<!DOCTYPE html>
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  <meta name="description" content="刘清政">
  <meta name="keyword" content="hexo-theme">
  
    <link rel="shortcut icon" href="/css/images/logo.png">
  
  <title>
    
      python/面向对象进阶/5-super()方法详解 | Justin-刘清政的博客
    
  </title>
  <link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/tomorrow.min.css" rel="stylesheet">
  
<link rel="stylesheet" href="/css/style.css">

  
    
<link rel="stylesheet" href="/css/plugins/gitment.css">

  
  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/geopattern/1.2.3/js/geopattern.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.js"></script>
  
    
<script src="/js/qrious.js"></script>

  
  
    
<script src="/js/gitment.js"></script>

  
  

  
<meta name="generator" content="Hexo 4.2.0"></head>
<div class="wechat-share">
  <img src="/css/images/logo.png" />
</div>

  <body>
    <header class="header fixed-header">
  <div class="header-container">
    <a class="home-link" href="/">
      <div class="logo"></div>
      <span>Justin-刘清政的博客</span>
    </a>
    <ul class="right-list">
      
        <li class="list-item">
          
            <a href="/" class="item-link">主页</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/tags/" class="item-link">标签</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/archives/" class="item-link">归档</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/about/" class="item-link">关于我</a>
          
        </li>
      
    </ul>
    <div class="menu">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </div>
    <div class="menu-mask">
      <ul class="menu-list">
        
          <li class="menu-item">
            
              <a href="/" class="menu-link">主页</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/tags/" class="menu-link">标签</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/archives/" class="menu-link">归档</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/about/" class="menu-link">关于我</a>
            
          </li>
        
      </ul>
    </div>
  </div>
</header>

    <div id="article-banner">
  <h2>python/面向对象进阶/5-super()方法详解</h2>



  <p class="post-date">2020-12-21</p>
    <!-- 不蒜子统计 -->
    <span id="busuanzi_container_page_pv" style='display:none' class="">
        <i class="icon-smile icon"></i> 阅读数：<span id="busuanzi_value_page_pv"></span>次
    </span>
  <div class="arrow-down">
    <a href="javascript:;"></a>
  </div>
</div>
<main class="app-body flex-box">
  <!-- Article START -->
  <article class="post-article">
    <section class="markdown-content"><h1 id="一、单独调用父类的方法"><a href="#一、单独调用父类的方法" class="headerlink" title="一、单独调用父类的方法"></a>一、单独调用父类的方法</h1><p>需求：编写一个类，然后再写一个子类进行继承，使用子类去调用父类的方法1。</p>
<p>使用方法1打印： 胖子老板，来包槟榔。</p>
<blockquote>
<p>那么先写一个胖子老板的父类，执行一下：</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">class FatFather(object):</span><br><span class="line">    def __init__(self, name):</span><br><span class="line">        print(&#39;FatFather的init开始被调用&#39;)</span><br><span class="line">        self.name &#x3D; name</span><br><span class="line">        print(&#39;FatFather的name是%s&#39; % self.name)</span><br><span class="line">        print(&#39;FatFather的init调用结束&#39;)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">def main():</span><br><span class="line">    ff &#x3D; FatFather(&quot;胖子老板的父亲&quot;)</span><br></pre></td></tr></table></figure>

<p>运行一下这个胖子老板父类的构造方法<strong>init</strong> 如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">if __name__ &#x3D;&#x3D; &quot;__main__&quot;:</span><br><span class="line">    main()</span><br></pre></td></tr></table></figure>



<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">FatFather的init开始被调用</span><br><span class="line">FatFather的name是胖子老板的父亲</span><br><span class="line">FatFather的init调用结束</span><br></pre></td></tr></table></figure>

<blockquote>
<p>好了，那么下面来写一个子类，也就是胖子老板类，继承上面的类</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"># 胖子老板的父类</span><br><span class="line">class FatFather(object):</span><br><span class="line">    def __init__(self, name):</span><br><span class="line">        print(&#39;FatFather的init开始被调用&#39;)</span><br><span class="line">        self.name &#x3D; name</span><br><span class="line">        print(&#39;调用FatFather类的name是%s&#39; % self.name)</span><br><span class="line">        print(&#39;FatFather的init调用结束&#39;)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"># 胖子老板类 继承 FatFather 类</span><br><span class="line">class FatBoss(FatFather):</span><br><span class="line">    def __init__(self, name, hobby):</span><br><span class="line">        print(&#39;胖子老板的类被调用啦！&#39;)</span><br><span class="line">        self.hobby &#x3D; hobby</span><br><span class="line">        FatFather.__init__(self, name)  # 直接调用父类的构造方法</span><br><span class="line">        print(&quot;%s 的爱好是 %s&quot; % (name, self.hobby))</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">def main():</span><br><span class="line">    #ff &#x3D; FatFather(&quot;胖子老板的父亲&quot;)</span><br><span class="line">    fatboss &#x3D; FatBoss(&quot;胖子老板&quot;, &quot;打斗地主&quot;)</span><br></pre></td></tr></table></figure>

<p>在这上面的代码中，我使用FatFather.<strong>init</strong>(self,name)直接调用父类的方法。<br>运行结果如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">if __name__ &#x3D;&#x3D; &quot;__main__&quot;:</span><br><span class="line">    main()</span><br></pre></td></tr></table></figure>



<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">胖子老板的类被调用啦！</span><br><span class="line">FatFather的init开始被调用</span><br><span class="line">调用FatFather类的name是胖子老板</span><br><span class="line">FatFather的init调用结束</span><br><span class="line">胖子老板 的爱好是 打斗地主</span><br></pre></td></tr></table></figure>

<h1 id="二、super-方法基本概念"><a href="#二、super-方法基本概念" class="headerlink" title="二、super() 方法基本概念"></a>二、super() 方法基本概念</h1><blockquote>
<p>除了直接使用 FatFather.<strong>init</strong>(self,name) 的方法，还可以使用super()方法来调用。</p>
</blockquote>
<p>那么首先需要看super()方法的描述和语法理解一下super() 方法的使用。</p>
<h2 id="2-1-描述"><a href="#2-1-描述" class="headerlink" title="2.1 描述"></a>2.1 描述</h2><p><strong>super() 函数是用于调用父类(超类)的一个方法。</strong></p>
<p>super 是用来解决多重继承问题的，直接用类名调用父类方法在使用单继承的时候没问题，但是如果使用多继承，会涉及到查找顺序（MRO）、重复调用（钻石继承）等种种问题。</p>
<p>MRO 就是类的方法解析顺序表, 其实也就是继承父类方法时的顺序表。</p>
<h2 id="2-2-语法"><a href="#2-2-语法" class="headerlink" title="2.2 语法"></a>2.2 语法</h2><p>以下是 super() 方法的语法:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">super(type[, object-or-type])</span><br></pre></td></tr></table></figure>

<blockquote>
<p>参数</p>
</blockquote>
<ul>
<li>type – 类</li>
<li>object-or-type – 类，一般是 self</li>
</ul>
<blockquote>
<p>Python3.x 和 Python2.x 的一个区别是: Python 3 可以使用直接使用 super().xxx 代替 super(Class, self).xxx :</p>
</blockquote>
<ul>
<li>Python3.x 实例：</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">class A:</span><br><span class="line">    pass</span><br><span class="line">class B(A):</span><br><span class="line">    def add(self, x):</span><br><span class="line">        super().add(x)</span><br></pre></td></tr></table></figure>

<ul>
<li>Python2.x 实例：</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">class A(object):   # Python2.x 记得继承 object</span><br><span class="line">    pass</span><br><span class="line">class B(A):</span><br><span class="line">    def add(self, x):</span><br><span class="line">        super(B, self).add(x)</span><br></pre></td></tr></table></figure>

<h2 id="2-3-单继承使用super"><a href="#2-3-单继承使用super" class="headerlink" title="2.3 单继承使用super()"></a>2.3 单继承使用super()</h2><ul>
<li>使用super() 方法来改写刚才胖子老板继承父类的 <strong>init</strong> 构造方法</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"># 胖子老板的父类</span><br><span class="line">class FatFather(object):</span><br><span class="line">    def __init__(self, name):</span><br><span class="line">        print(&#39;FatFather的init开始被调用&#39;)</span><br><span class="line">        self.name &#x3D; name</span><br><span class="line">        print(&#39;调用FatFather类的name是%s&#39; % self.name)</span><br><span class="line">        print(&#39;FatFather的init调用结束&#39;)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"># 胖子老板类 继承 FatFather 类</span><br><span class="line">class FatBoss(FatFather):</span><br><span class="line">    def __init__(self, name, hobby):</span><br><span class="line">        print(&#39;胖子老板的类被调用啦！&#39;)</span><br><span class="line">        self.hobby &#x3D; hobby</span><br><span class="line">        #FatFather.__init__(self,name)   # 直接调用父类的构造方法</span><br><span class="line">        super().__init__(name)</span><br><span class="line">        print(&quot;%s 的爱好是 %s&quot; % (name, self.hobby))</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">def main():</span><br><span class="line">    #ff &#x3D; FatFather(&quot;胖子老板的父亲&quot;)</span><br><span class="line">    fatboss &#x3D; FatBoss(&quot;胖子老板&quot;, &quot;打斗地主&quot;)</span><br></pre></td></tr></table></figure>

<p>从上面使用super方法的时候，因为是单继承，直接就可以使用了。<br>运行如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">if __name__ &#x3D;&#x3D; &quot;__main__&quot;:</span><br><span class="line">    main()</span><br></pre></td></tr></table></figure>



<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">胖子老板的类被调用啦！</span><br><span class="line">FatFather的init开始被调用</span><br><span class="line">调用FatFather类的name是胖子老板</span><br><span class="line">FatFather的init调用结束</span><br><span class="line">胖子老板 的爱好是 打斗地主</span><br></pre></td></tr></table></figure>

<p>那么为什么说<strong>单继承</strong>直接使用就可以呢？因为super()方法如果多继承的话，会涉及到一个MRO(<strong>继承父类方法时的顺序表</strong>) 的调用排序问题。</p>
<blockquote>
<p>下面可以打印一下看看单继承的MRO顺序(FatBoss.<strong>mro</strong>)。</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"># 胖子老板的父类</span><br><span class="line">class FatFather(object):</span><br><span class="line">    def __init__(self, name):</span><br><span class="line">        print(&#39;FatFather的init开始被调用&#39;)</span><br><span class="line">        self.name &#x3D; name</span><br><span class="line">        print(&#39;调用FatFather类的name是%s&#39; % self.name)</span><br><span class="line">        print(&#39;FatFather的init调用结束&#39;)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"># 胖子老板类 继承 FatFather 类</span><br><span class="line">class FatBoss(FatFather):</span><br><span class="line">    def __init__(self, name, hobby):</span><br><span class="line">        print(&#39;胖子老板的类被调用啦！&#39;)</span><br><span class="line">        self.hobby &#x3D; hobby</span><br><span class="line">        #FatFather.__init__(self,name)   # 直接调用父类的构造方法</span><br><span class="line">        super().__init__(name)</span><br><span class="line">        print(&quot;%s 的爱好是 %s&quot; % (name, self.hobby))</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">def main():</span><br><span class="line"></span><br><span class="line">    print(&quot;打印FatBoss类的MRO&quot;)</span><br><span class="line">    print(FatBoss.__mro__)</span><br><span class="line"></span><br><span class="line">    print()</span><br><span class="line">    print(&quot;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D; 下面按照 MRO 顺序执行super方法 &#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&quot;)</span><br><span class="line">    fatboss &#x3D; FatBoss(&quot;胖子老板&quot;, &quot;打斗地主&quot;)</span><br></pre></td></tr></table></figure>

<p>上面的代码使用 FatBoss.<strong>mro</strong> 可以打印出 FatBoss这个类经过 python解析器的 C3算法计算过后的继承调用顺序。<br>运行如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">if __name__ &#x3D;&#x3D; &quot;__main__&quot;:</span><br><span class="line">    main()</span><br></pre></td></tr></table></figure>



<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">打印FatBoss类的MRO</span><br><span class="line">(&lt;class &#39;__main__.FatBoss&#39;&gt;, &lt;class &#39;__main__.FatFather&#39;&gt;, &lt;class &#39;object&#39;&gt;)</span><br><span class="line"></span><br><span class="line">&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D; 下面按照 MRO 顺序执行super方法 &#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;</span><br><span class="line">胖子老板的类被调用啦！</span><br><span class="line">FatFather的init开始被调用</span><br><span class="line">调用FatFather类的name是胖子老板</span><br><span class="line">FatFather的init调用结束</span><br><span class="line">胖子老板 的爱好是 打斗地主</span><br></pre></td></tr></table></figure>

<p>从上面的结果 (&lt;class ‘<strong>main</strong>.FatBoss’&gt;, &lt;class ‘<strong>main</strong>.FatFather’&gt;, &lt;class ‘object’&gt;) 可以看出，super() 方法在 FatBoss 会直接调用父类是 FatFather ，所以单继承是没问题的。</p>
<p>那么如果多继承的话，会有什么问题呢？</p>
<h2 id="2-4-多继承使用super"><a href="#2-4-多继承使用super" class="headerlink" title="2.4 多继承使用super()"></a>2.4 多继承使用super()</h2><p>假设再写一个胖子老板的女儿类，和 胖子老板的老婆类，此时女儿需要同时继承 两个类（胖子老板类，胖子老板老婆类）。</p>
<p>因为胖子老板有一个爱好，胖子老板的老婆需要干活干家务，那么女儿需要帮忙同时兼顾。</p>
<p>此时女儿就是需要继承使用这两个父类的方法了，那么该如何去写呢？</p>
<p>下面来看看实现代码：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><span class="line"># 胖子老板的父类</span><br><span class="line">class FatFather(object):</span><br><span class="line">    def __init__(self, name, *args, **kwargs):</span><br><span class="line">        print()</span><br><span class="line">        print(&quot;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D; 开始调用 FatFather  &#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&quot;)</span><br><span class="line">        print(&#39;FatFather的init开始被调用&#39;)</span><br><span class="line">        self.name &#x3D; name</span><br><span class="line">        print(&#39;调用FatFather类的name是%s&#39; % self.name)</span><br><span class="line">        print(&#39;FatFather的init调用结束&#39;)</span><br><span class="line">        print()</span><br><span class="line">        print(&quot;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D; 结束调用 FatFather  &#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&quot;)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"># 胖子老板类 继承 FatFather 类</span><br><span class="line">class FatBoss(FatFather):</span><br><span class="line">    def __init__(self, name, hobby, *args, **kwargs):</span><br><span class="line">        print()</span><br><span class="line">        print(&quot;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D; 开始调用 FatBoss  &#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&quot;)</span><br><span class="line">        print(&#39;胖子老板的类被调用啦！&#39;)</span><br><span class="line">        #super().__init__(name)</span><br><span class="line">        ## 因为多继承传递的参数不一致，所以使用不定参数</span><br><span class="line">        super().__init__(name, *args, **kwargs)</span><br><span class="line">        print(&quot;%s 的爱好是 %s&quot; % (name, hobby))</span><br><span class="line">        print()</span><br><span class="line">        print(&quot;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D; 结束调用 FatBoss  &#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&quot;)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"># 胖子老板的老婆类 继承 FatFather类</span><br><span class="line">class FatBossWife(FatFather):</span><br><span class="line">    def __init__(self, name, housework, *args, **kwargs):</span><br><span class="line">        print()</span><br><span class="line">        print(&quot;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D; 开始调用 FatBossWife  &#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&quot;)</span><br><span class="line">        print(&#39;胖子老板的老婆类被调用啦！要学会干家务&#39;)</span><br><span class="line">        #super().__init__(name)</span><br><span class="line">        ## 因为多继承传递的参数不一致，所以使用不定参数</span><br><span class="line">        super().__init__(name, *args, **kwargs)</span><br><span class="line">        print(&quot;%s 需要干的家务是 %s&quot; % (name, housework))</span><br><span class="line">        print()</span><br><span class="line">        print(&quot;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D; 结束调用 FatBossWife  &#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&quot;)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"># 胖子老板的女儿类 继承 FatBoss FatBossWife类</span><br><span class="line">class FatBossGril(FatBoss, FatBossWife):</span><br><span class="line">    def __init__(self, name, hobby, housework):</span><br><span class="line">        print(&#39;胖子老板的女儿类被调用啦！要学会干家务，还要会帮胖子老板斗地主&#39;)</span><br><span class="line">        super().__init__(name, hobby, housework)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">def main():</span><br><span class="line"></span><br><span class="line">    print(&quot;打印FatBossGril类的MRO&quot;)</span><br><span class="line">    print(FatBossGril.__mro__)</span><br><span class="line"></span><br><span class="line">    print()</span><br><span class="line">    print(&quot;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D; 下面按照 MRO 顺序执行super方法 &#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&quot;)</span><br><span class="line">    gril &#x3D; FatBossGril(&quot;胖子老板&quot;, &quot;打斗地主&quot;, &quot;拖地&quot;)</span><br></pre></td></tr></table></figure>

<p>运行结果如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">if __name__ &#x3D;&#x3D; &quot;__main__&quot;:</span><br><span class="line">    main()</span><br></pre></td></tr></table></figure>



<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">打印FatBossGril类的MRO</span><br><span class="line">(&lt;class &#39;__main__.FatBossGril&#39;&gt;, &lt;class &#39;__main__.FatBoss&#39;&gt;, &lt;class &#39;__main__.FatBossWife&#39;&gt;, &lt;class &#39;__main__.FatFather&#39;&gt;, &lt;class &#39;object&#39;&gt;)</span><br><span class="line"></span><br><span class="line">&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D; 下面按照 MRO 顺序执行super方法 &#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;</span><br><span class="line">胖子老板的女儿类被调用啦！要学会干家务，还要会帮胖子老板斗地主</span><br><span class="line"></span><br><span class="line">&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D; 开始调用 FatBoss  &#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;</span><br><span class="line">胖子老板的类被调用啦！</span><br><span class="line"></span><br><span class="line">&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D; 开始调用 FatBossWife  &#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;</span><br><span class="line">胖子老板的老婆类被调用啦！要学会干家务</span><br><span class="line"></span><br><span class="line">&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D; 开始调用 FatFather  &#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;</span><br><span class="line">FatFather的init开始被调用</span><br><span class="line">调用FatFather类的name是胖子老板</span><br><span class="line">FatFather的init调用结束</span><br><span class="line"></span><br><span class="line">&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D; 结束调用 FatFather  &#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;</span><br><span class="line">胖子老板 需要干的家务是 拖地</span><br><span class="line"></span><br><span class="line">&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D; 结束调用 FatBossWife  &#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;</span><br><span class="line">胖子老板 的爱好是 打斗地主</span><br><span class="line"></span><br><span class="line">&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D; 结束调用 FatBoss  &#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;&#x3D;</span><br></pre></td></tr></table></figure>

<p>从上面的运行结果来看，我特意给每个类的调用开始以及结束都进行打印标识，可以看到。</p>
<p>每个类开始调用是根据MRO顺序进行开始，然后逐个进行结束的。</p>
<p>还有就是由于因为需要继承不同的父类，参数不一定。</p>
<p>所以，所有的父类都应该加上不定参数<em>args , *</em>kwargs ，不然参数不对应是会报错的。</p>
<h1 id="三、注意事项"><a href="#三、注意事项" class="headerlink" title="三、注意事项"></a>三、注意事项</h1><ul>
<li>super().<strong>init</strong>相对于类名.<strong>init</strong>，在单继承上用法基本无差</li>
<li>但在多继承上有区别，super方法能保证每个父类的方法只会执行一次，而使用类名的方法会导致方法被执行多次，可以尝试写个代码来看输出结果</li>
<li>多继承时，使用super方法，对父类的传参数，应该是由于python中super的算法导致的原因，必须把参数全部传递，否则会报错</li>
<li>单继承时，使用super方法，则不能全部传递，只能传父类方法所需的参数，否则会报错</li>
<li>多继承时，相对于使用类名.<strong>init</strong>方法，要把每个父类全部写一遍, 而使用super方法，只需写一句话便执行了全部父类的方法，这也是为何多继承需要全部传参的一个原因</li>
</ul>
<h1 id="四、练习"><a href="#四、练习" class="headerlink" title="四、练习"></a>四、练习</h1><blockquote>
<p>以下的代码的输出将是什么? 说出你的答案并解释。</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">class Parent(object):</span><br><span class="line">    x &#x3D; 1</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">class Child1(Parent):</span><br><span class="line">    pass</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">class Child2(Parent):</span><br><span class="line">    pass</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">print(Parent.x, Child1.x, Child2.x)</span><br></pre></td></tr></table></figure>

<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">1 1 1</span><br></pre></td></tr></table></figure>

<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Child1.x &#x3D; 2</span><br><span class="line">print(Parent.x, Child1.x, Child2.x)</span><br></pre></td></tr></table></figure>

<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">1 2 1</span><br></pre></td></tr></table></figure>

<ul>
<li>注意：Child1已经拥有了属于自己的x</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Parent.x &#x3D; 3</span><br><span class="line">print(Parent.x, Child1.x, Child2.x)</span><br></pre></td></tr></table></figure>



<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">3 2 3</span><br></pre></td></tr></table></figure></section>
    <!-- Tags START -->
    
    <!-- Tags END -->
    <!-- NAV START -->
    
  <div class="nav-container">
    <!-- reverse left and right to put prev and next in a more logic postition -->
    
      <a class="nav-left" href="/python/%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E9%AB%98%E9%98%B6/18-%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E9%AB%98%E7%BA%A7%E5%B0%8F%E7%BB%93/">
        <span class="nav-arrow">← </span>
        
          python/面向对象高阶/18-面向对象高级小结
        
      </a>
    
    
      <a class="nav-right" href="/python/%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E8%BF%9B%E9%98%B6/8-%E7%B1%BB%E7%9A%84property%E7%89%B9%E6%80%A7/">
        
          python/面向对象进阶/8-类的property特性
        
        <span class="nav-arrow"> →</span>
      </a>
    
  </div>

    <!-- NAV END -->
    <!-- 打赏 START -->
    
      <div class="money-like">
        <div class="reward-btn">
          赏
          <span class="money-code">
            <span class="alipay-code">
              <div class="code-image"></div>
              <b>使用支付宝打赏</b>
            </span>
            <span class="wechat-code">
              <div class="code-image"></div>
              <b>使用微信打赏</b>
            </span>
          </span>
        </div>
        <p class="notice">点击上方按钮,请我喝杯咖啡！</p>
      </div>
    
    <!-- 打赏 END -->
    <!-- 二维码 START -->
    
      <div class="qrcode">
        <canvas id="share-qrcode"></canvas>
        <p class="notice">扫描二维码，分享此文章</p>
      </div>
    
    <!-- 二维码 END -->
    
      <!-- Gitment START -->
      <div id="comments"></div>
      <!-- Gitment END -->
    
  </article>
  <!-- Article END -->
  <!-- Catalog START -->
  
    <aside class="catalog-container">
  <div class="toc-main">
  <!-- 不蒜子统计 -->
    <strong class="toc-title">目录</strong>
    
      <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#一、单独调用父类的方法"><span class="toc-nav-text">一、单独调用父类的方法</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#二、super-方法基本概念"><span class="toc-nav-text">二、super() 方法基本概念</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#2-1-描述"><span class="toc-nav-text">2.1 描述</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#2-2-语法"><span class="toc-nav-text">2.2 语法</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#2-3-单继承使用super"><span class="toc-nav-text">2.3 单继承使用super()</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#2-4-多继承使用super"><span class="toc-nav-text">2.4 多继承使用super()</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#三、注意事项"><span class="toc-nav-text">三、注意事项</span></a></li><li class="toc-nav-item toc-nav-level-1"><a class="toc-nav-link" href="#四、练习"><span class="toc-nav-text">四、练习</span></a></li></ol>
    
  </div>
</aside>
  
  <!-- Catalog END -->
</main>

<script>
  (function () {
    var url = 'http://www.liuqingzheng.top/python/面向对象进阶/5-super()方法详解/';
    var banner = ''
    if (banner !== '' && banner !== 'undefined' && banner !== 'null') {
      $('#article-banner').css({
        'background-image': 'url(' + banner + ')'
      })
    } else {
      $('#article-banner').geopattern(url)
    }
    $('.header').removeClass('fixed-header')

    // error image
    $(".markdown-content img").on('error', function() {
      $(this).attr('src', 'http://file.muyutech.com/error-img.png')
      $(this).css({
        'cursor': 'default'
      })
    })

    // zoom image
    $(".markdown-content img").on('click', function() {
      var src = $(this).attr('src')
      if (src !== 'http://file.muyutech.com/error-img.png') {
        var imageW = $(this).width()
        var imageH = $(this).height()

        var zoom = ($(window).width() * 0.95 / imageW).toFixed(2)
        zoom = zoom < 1 ? 1 : zoom
        zoom = zoom > 2 ? 2 : zoom
        var transY = (($(window).height() - imageH) / 2).toFixed(2)

        $('body').append('<div class="image-view-wrap"><div class="image-view-inner"><img src="'+ src +'" /></div></div>')
        $('.image-view-wrap').addClass('wrap-active')
        $('.image-view-wrap img').css({
          'width': `${imageW}`,
          'transform': `translate3d(0, ${transY}px, 0) scale3d(${zoom}, ${zoom}, 1)`
        })
        $('html').css('overflow', 'hidden')

        $('.image-view-wrap').on('click', function() {
          $(this).remove()
          $('html').attr('style', '')
        })
      }
    })
  })();
</script>


  <script>
    var qr = new QRious({
      element: document.getElementById('share-qrcode'),
      value: document.location.href
    });
  </script>



  <script>
    var gitmentConfig = "liuqingzheng";
    if (gitmentConfig !== 'undefined') {
      var gitment = new Gitment({
        id: "python/面向对象进阶/5-super()方法详解",
        owner: "liuqingzheng",
        repo: "FuckBlog",
        oauth: {
          client_id: "32a4076431cf39d0ecea",
          client_secret: "94484bd79b3346a949acb2fda3c8a76ce16990c6"
        },
        theme: {
          render(state, instance) {
            const container = document.createElement('div')
            container.lang = "en-US"
            container.className = 'gitment-container gitment-root-container'
            container.appendChild(instance.renderHeader(state, instance))
            container.appendChild(instance.renderEditor(state, instance))
            container.appendChild(instance.renderComments(state, instance))
            container.appendChild(instance.renderFooter(state, instance))
            return container;
          }
        }
      })
      gitment.render(document.getElementById('comments'))
    }
  </script>




    <div class="scroll-top">
  <span class="arrow-icon"></span>
</div>
    <footer class="app-footer">
<!-- 不蒜子统计 -->
<span id="busuanzi_container_site_pv">
     本站总访问量<span id="busuanzi_value_site_pv"></span>次
</span>
<span class="post-meta-divider">|</span>
<span id="busuanzi_container_site_uv" style='display:none'>
     本站访客数<span id="busuanzi_value_site_uv"></span>人
</span>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>



  <p class="copyright">
    &copy; 2021 | Proudly powered by <a href="https://www.cnblogs.com/xiaoyuanqujing" target="_blank">小猿取经</a>
    <br>
    Theme by <a href="https://www.cnblogs.com/xiaoyuanqujing" target="_blank" rel="noopener">小猿取经</a>
  </p>
</footer>

<script>
  function async(u, c) {
    var d = document, t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
    s.parentNode.insertBefore(o, s);
  }
</script>
<script>
  async("//cdnjs.cloudflare.com/ajax/libs/fastclick/1.0.6/fastclick.min.js", function(){
    FastClick.attach(document.body);
  })
</script>

<script>
  var hasLine = 'true';
  async("//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js", function(){
    $('figure pre').each(function(i, block) {
      var figure = $(this).parents('figure');
      if (hasLine === 'false') {
        figure.find('.gutter').hide();
      }
      var lang = figure.attr('class').split(' ')[1] || 'code';
      var codeHtml = $(this).html();
      var codeTag = document.createElement('code');
      codeTag.className = lang;
      codeTag.innerHTML = codeHtml;
      $(this).attr('class', '').empty().html(codeTag);
      figure.attr('data-lang', lang.toUpperCase());
      hljs.highlightBlock(block);
    });
  })
</script>





<!-- Baidu Tongji -->

<script>
    var _baId = 'c5fd96eee1193585be191f318c3fa725';
    // Originial
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?" + _baId;
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
</script>


<script src="/js/script.js"></script>


<script src="/js/search.js"></script>


<script src="/js/load.js"></script>



  <span class="local-search local-search-google local-search-plugin" style="right: 50px;top: 70px;;position:absolute;z-index:2;">
      <input type="search" placeholder="站内搜索" id="local-search-input" class="local-search-input-cls" style="">
      <div id="local-search-result" class="local-search-result-cls"></div>
  </span>


  </body>
</html>